#include "hvtcpserver.h"
#include "log.h"
#include "CustomEvent.h"
#include "mainwindow.h"

HvTcpServer::HvTcpServer(QObject *parent) : QObject(parent), server(NULL)
{
}

HvTcpServer::~HvTcpServer()
{
    stop();
}

bool HvTcpServer::start(quint16 port)
{
    if(server)
    {
        goto __false;
    }

    server = new hv::TcpServer;

    // 创建socket监听
    if(server->createsocket(port) < 0)
    {
        goto __cleanup;
    }

    // 设置线程数量
    server->setThreadNum(1);

    // 注册连接断开的回调函数
    server->onConnection = [=](const hv::SocketChannelPtr& channel)
    {
        QString key(channel->peeraddr().data());
        if(channel->isConnected())
        {
            DataProcessService* service = new DataProcessService(channel);
            services.insert(key, service);

            ConnectEvent e(channel);
            g_MainWnd->postEvent(e);
        }else
        {
            DataProcessService* service = services.value(key);
            services.remove(key);
            delete service;

            DisconnectEvent e(channel);
            g_MainWnd->postEvent(e);
        }
    };

    // 注册数据接收回调函数
    server->onMessage = [=](const hv::SocketChannelPtr &channel, hv::Buffer *buf)
    {
        QString key(channel->peeraddr().data());
        services.value(key)->process(buf->data(), buf->size());
    };

    // 启动服务器
    server->start();

    goto __true;

__true:
    return true;

__cleanup:
    stop();

__false:
    return false;
}

void HvTcpServer::stop()
{
    SAFE_DELETE(server);
}
